﻿function BangoPoster(postProfile, postUrl, userAgent, sendAsync, useOfflineStorage) {

	this.PostProfile;
	this.PostURL;
	this.SendAsync;
	this.UseOfflineStorage;
	this.UserAgent;

	this.PostProfile = postProfile;
	this.PostURL = postUrl;
	this.SendAsync = sendAsync;
	this.UseOfflineStorage = useOfflineStorage;
	this.UserAgent = userAgent;

	var ajaxPost = null;

	this.postEventsForProfile = function () {
		var asyncSending;

		try {
			if (navigator.onLine) {
				if (this.UserAgent == null || this.UserAgent == "" || this.UserAgent == undefined) {
					this.UserAgent = navigator.userAgent;
				}

				asyncSending = true;
				if (this.SendAsync == false) {
					asyncSending = false;
				}

				if (window.XDomainRequest) {
					ajaxPost = new XDomainRequest();
				}
				else if (window.XMLHttpRequest) {
					ajaxPost = new XMLHttpRequest();
				}
				else if (window.ActiveXObject) {
					ajaxPost = new ActiveXObject("Microsoft.XMLHTTP");
				}

				if (ajaxPost) {
					ajaxPost.onreadystatechange = onReadyStateChange;
					ajaxPost.ontimeout = onTimeout;
					ajaxPost.open("POST", this.PostURL, asyncSending);
					ajaxPost.send(JSON.stringify(this.PostProfile));
				}
			}
		}
		catch (ex) {
			clearIsPostingFlag(postProfile);
		}
	};

	onTimeout = function () {
		clearIsPostingFlag(postProfile);
	};

	onReadyStateChange = function () {
		var result;
		try {
			// readyStatus=4 Means completed
			if (ajaxPost.readyState == 4) {
				/*
				 * get HTTP Data
				 * first check, if there is a response at all,
				 * then if okay, update events to say they have been posted
				 */
				result = ajaxPost.responseText;
				if (result && result.length > 1 && result.substring(0, 2) == "OK") {
					updateEventsPosted(postProfile);
				}
				else {
					clearIsPostingFlag(postProfile);
				}
			}
		}
		catch (ex) {
		}

	};

	updateEventsPosted = function (postProfile) {
		BangoStorage.updateEventsPosted(useOfflineStorage, postProfile);
	};

	clearIsPostingFlag = function (postProfile) {
		BangoStorage.clearIsPostingFlag(useOfflineStorage, postProfile);
	};
};
